<?php

namespace app\model;

use app\stateData;
use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;

class OrderEnterpriseCertificateBusiness extends Model
{

    /**
     * 企业证书业务
     */
    use SoftDelete;

    protected $createTime = 'create_date';
    protected $deleteTime = 'delete_date';

    public function getIds()
    {
        $list = self::select()->toArray();
        return array_column($list, 'id');
    }

    public function chargeback()
    {
        return $this->hasOne(OrderDealChargeback::class, 'certificate_code', 'certificate_code')
            ->bind([
                'order_company_id',
                'chargeback_performance' => 'performance',
                'charge_back_date',
                'reason',
                'get_uid_up_logoff_file',
                'notifier_get_uid',
                'push_uidup_logoff_file',
                'notifier_push_uid',
                'b_certificate_is_conpany',
                'chargeback_create_date' => 'create_date',
                'chargeback_type' => 'type'
            ])->order('create_date DESC');
    }

    public function getStatusAttr($name): array
    {
        return [
            'id' => $name,
            'text' => stateData::$_enter_business[$name]
        ];
    }

    public function getGetOrgAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new UserOrganization())->getStructureName($name) ?: ''
        ];
    }

    public function getGetUidAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new User())->getIdNickName($name) ?: ''
        ];
    }

    public function getOutOrgAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new UserOrganization())->getStructureName($name) ?: ''
        ];
    }

    public function getOutUidAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new User())->getIdNickName($name) ?: ''
        ];
    }

    public function getInformationFileAttr($value)
    {
        if (empty($value)) return "";
        $arr = explode(',', $value);
        $value = '';
        foreach ($arr as &$v) {
            $value .= config('file.url') . $v . ',';
        }
        return rtrim($value, ',');
    }

    public function getContractFileAttr($value)
    {
        if (empty($value)) return "";
        $arr = explode(',', $value);
        $value = '';
        foreach ($arr as &$v) {
            $value .= config('file.url') . $v . ',';
        }
        return rtrim($value, ',');
    }

    public function getBusinessIdAttr($name)
    {
        return [
            'id' => $name,
            'text' => (new SystemBusiness)->getBusinessIdTitle($name) ?: ''
        ];
    }

    public function getBusinessCategoryAttr($name, $data)
    {
        return (new SystemBusiness)->getBusinessCategoryModel($data['business_id']) ?: '';
    }

    public function getResponsibilityUidAttr($name)
    {
        return [
            'id' => $name,
            'text' => (new User)->getIdNickName($name) ?: ''
        ];
    }

    public function getCertificateLeixingAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return $name;
    }

    public function getCertificateLeibieAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return $name;
    }

    public function getCertificateDengjiAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return $name;
    }

    public function getCertificateZhuanyeAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return $name;
    }

    public function getSfkStatusAttr($name)
    {
        return [
            'id' => $name ?: '',
            'text' => stateData::$_sfk_status[$name]
        ];
    }

    public function getPerformanceIdAttr($name)
    {
        return $name ?: '';
    }

    public function getInformationFileNameAttr($name)
    {
        if (!$name) return '';
        return $name;
    }

    public function getContractFileNameAttr($name)
    {
        if (!$name) return '';
        return $name;
    }

    public function getSaleDateAttr($name)
    {
        if ($name == '0000-00-00 00:00:00') {
            return "";
        }
        return $name;
    }

//    public function getSalePriceAttr($name)
//    {
//        if ($name == '0.00'){
//            return '';
//        }
//        return $name;
//    }

//    public function getCostPriceAttr($name)
//    {
//        if ($name == '0.00'){
//            return '';
//        }
//        return $name;
//    }

    public function getShUidAttr($name)
    {
        return [
            'id' => $name ?: '',
            'text' => (new User)->getIdNickName($name) ?: ''
        ];
    }

    public function getSfkWcDateAttr($name)
    {
        if (!$name || $name == '0000-00-00 00:00:00') return '';
        return date ('Y-m-d',strtotime ($name));
    }

    public function business()
    {
        return $this->hasOne(SystemBusiness::class, 'id', 'business_id')->bind(['business_name', 'business_name']);
    }

    public function addDataModel($data)
    {
        return self::create($data);
    }

    public function getDataIds($idArr)
    {
        if (is_array($idArr)) {
            $idArr = implode($idArr, ',');
        }

        $list = $this
            ->whereRaw('get_uid IN (' . $idArr . ') OR out_uid IN (' . $idArr . ') OR responsibility_uid IN (' . $idArr . ') OR sh_uid IN (' . $idArr . ')')
            ->select()->toArray();

        return array_column($list, 'id');
    }

    /**
     * 查询ID范围数据
     */
    public function getRandDataModel($idArr)
    {
        //排除录单中的数据
//        return $this->where(function ($query) use ($idArr) {
//            $query->where('get_uid', 'in', $idArr)->whereOr('out_uid', 'in', $idArr);
//        })
//            ->where('status', '<>', 11)
//            ->select()
//            ->toArray();
        return $this->where(function ($query) use ($idArr) {
            $query->where('get_uid', 'in', $idArr)->whereOr('out_uid', 'in', $idArr);
        })
            ->where('status', '<>', 11)
            ->column ('id,certificate_code,sale_date');
    }

    /**
     * 管理获取企业业务列表
     * @param int $page
     * @return \app\model\OrderEnterpriseCertificateBusiness[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDataModel($page, $pageNum, $ids)
    {
        return $this->where('id', 'in', $ids)->order('create_date DESC')->select()->toArray();
    }

    public function getExcelModel($id)
    {
        return $this->whereIn('id', $id)->order('create_date DESC')->select()->toArray();
    }

    public function getDataCountModel($ids)
    {
        return $this->where('id', 'in', $ids)->count();
    }

    public function getThatPersonDataIds($id)
    {
//        $list = $this->whereOr(['get_uid' => $id])->whereOr(['responsibility_uid' => $id])->whereOr(['submit_id'=>$id])->whereOr(['out_uid' => $id])->order('create_date DESC')->select()->toArray();
        $list = $this->order('create_date DESC')->select()->toArray();
        return array_column($list, 'id');
    }

    /**
     * 个人获取企业业务列表
     * @param $id
     * @param $page
     * @return \app\model\OrderEnterpriseCertificateBusiness[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getThatPersonDataModel($id, $ids, $page = 1)
    {
//        return $this->where(function ($query)use($id){
//            $query->whereOr(['get_uid' => $id])->whereOr(['responsibility_uid' => $id])->whereOr(['out_uid' => $id])->whereOr(['submit_id'=>$id]);
//        })->where('id', 'in', $ids)->order('create_date DESC')->page($page, stateData::$_page)->select();
        $data = $this->with('chargeback')->where('id', 'in', $ids)->order('create_date DESC')->select()->toArray();

        //判断通知人 审批人等是否是当前用户
        $result = [];
        foreach ($data as $k => $item) {
            if ($item['get_uid']['id'] == $id || $item['responsibility_uid']['id'] == $id || $item['out_uid']['id'] == $id || $item['submit_id'] == $id || $item['notifier_get_uid'] == $id || $item['notifier_push_uid'] == $id || $item['sh_uid']['id'] == $id) {
                $result[] = $item;
            }
        }

        return array_values($result);
    }

    public function getThatPersonDataCountModel($id, $ids): int
    {
        return $this->where(function ($query) use ($id) {
            $query->where(['get_uid' => $id])->whereOr(['responsibility_uid' => $id]);
        })->where('id', 'in', $ids)->count();
    }

    /**
     * 删除业务信息
     * @param $id
     * @return bool
     */
    public function delIdData($id)
    {
        return self::destroy($id);
    }

    /**
     * 修改业务信息
     * @param $data
     * @return \app\model\OrderEnterpriseCertificateBusiness
     */
    public function editDataModel($data)
    {
        return self::update($data);
    }

    /**
     * 查询id相关业务
     * @param $id
     * @return \app\model\OrderEnterpriseCertificateBusiness|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getWhereIdDataModel($id)
    {
        $data = $this->where(['id' => $id])->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }

    public function getWhereIdDataSelectModel($id, $cer)
    {
        return $this->where(['id' => $id, 'certificate_code' => $cer])->select()->toArray();
    }

    /**
     * 获取订单业绩归属人
     */
    public function getOrderPerformanceUidModel($id,$certificateCode)
    {
        return $this->where (['certificate_code'=>$certificateCode,'id'=>$id])->value ('performance_uid');
    }

    /**
     * 通过证书编码查询证书详情
     * @param $cer
     * @return array|null
     */
    public function getCerFieldDataModel($cer): ?array
    {
        $data = $this->where(['certificate_code' => $cer])->field('id,certificate_code,business_id,create_date,get_org,get_uid,status,sale_price,cost_price')->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }

    /**
     * 通过证书编号查询某个字段
     * @param $cer
     * @param $field
     * @return mixed
     */
    public function getCerDataPersonModel($cer,$field)
    {
        return $this->where(['certificate_code' => $cer])->value($field);
    }
    public function getCerDataModel($cer)
    {
        $data = $this->where(['certificate_code' => $cer])->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }


    public function getWhereEnterpriseNameModel($enterName)
    {
        $data = $this->where(['enterprise_name' => $enterName])->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }

    /**
     * 完成订单操作
     * @param $id
     * @return \app\model\OrderEnterpriseCertificateBusiness
     */
    public function completeOperateModel($id)
    {
        return $this->where(['id' => $id])->update(['status' => -1]);
    }

    /**
     * 完成订单收付款
     * @param $id
     * @return \app\model\OrderEnterpriseCertificateBusiness
     */
    public function completeOrderSFKModel($id)
    {
        return $this->where(['id' => $id])->update(['sfk_status' => 2, 'sfk_wc_date' => date('Y-m-d H:i:s')]);
    }

    /**
     * 完成后点击返回按钮 状态改为未完成 完成时间改为空
     * @param $id
     * @return OrderEnterpriseCertificateBusiness
     */
    public function backCompleteOrderSFKModel($id)
    {
        return $this->where(['id' => $id])->update(['sfk_status' => 1, 'sfk_wc_date' => null]);
    }

    /**
     * 修改订单状态为录单中
     * @param $id
     * @return \app\model\OrderEnterpriseCertificateBusiness
     */
    public function saveStatusInitModel($id)
    {
        return $this->where(['id' => $id])->update(['status' => 11]);
    }

    /**
     * 查询聘用单位的成交数据
     * @param $title
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getEmployTitleDataModel($title): array
    {
        return $this->where(['enterprise_name' => $title, 'sfk_status' => 1])->select()->toArray();
    }

    /**
     * 获取证书应收款
     * @param $cer
     * @return array|null
     */
    public function getFinanceFieldFindModel($cer)
    {
        $data = $this->where(['certificate_code' => $cer])->field('certificate_code,id,sale_price as receivable,cost_price,performance_uid,sale_date')->findOrEmpty();
//        return Db::table('order_enterprise_certificate_business')->where(['certificate_code' => $cer])->find ();

        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }

    /**
     * 修改订单状态为已退单
     * @param $cer
     * @param int $status
     * @return \app\model\OrderEnterpriseCertificateBusiness
     */
    public function setStatusBack($cer, int $status = 2)
    {
        return $this->where(['certificate_code' => $cer])->update(['status' => $status]);
    }

    /**
     * 获取出证价 收证价
     * @return array|float|int|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSummaryModel($startDate, $endDate, $uidArr)
    {
        //查询时间段内成交库的certificate_code
        //拼接whereIn条件
        $performance_sum = 0;
//        $cerCode = Db::table('order_deal')->whereBetweenTime ('create_date',$startDate,$endDate)->column('certificate_code');
        if (empty($startDate) || empty($endDate)) {
            $data = $this->whereRaw('status=1 OR status=2 OR status = 12')->field('id,performance,performance_uid')->select()->toArray();
        } else {
//            $data = $this->whereRaw('status=1 OR status=2 OR status = 12')->whereIn ('certificate_code',$cerCode)->field('performance,performance_uid')->select()->toArray ();
            $data = $this->whereRaw('status=1 OR status=2 OR status = 12')->whereBetweenTime('create_date', $startDate, $endDate)->field('id,performance,performance_uid')->select()->toArray();
        }

        if (!is_array($uidArr)) {
            $uidArr = explode(',', $uidArr);
        }
        if ($data) {
            foreach ($data as &$item) {
                //业绩归属人字符串转数组
                $idArr = explode(',', $item['performance_uid']);
                $idCount = count($idArr);
                foreach ($idArr as $val) {
                    if (in_array($val, $uidArr)) {
                        $performance_sum += $item['performance'] / $idCount;
                    }
                }
            }
        }

        return $performance_sum;
    }

    /**
     * Ⅱ类业绩排行榜（滚动）
     * @param $startDate
     * @param $endDate
     * @param $idArr
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPhbModel($startDate, $endDate, $idArr)
    {

        $orderDealChargebackModel = new OrderDealChargeback();
        $tdData = $orderDealChargebackModel->getBetDateTypeModel($startDate,$endDate);
        $data = $this->whereBetweenTime('sale_date', $startDate, $endDate)
            ->whereRaw('status = 1 OR status = 12 OR status = 2')
            ->field('id,performance_uid,performance,certificate_code')
            ->select()->toArray();
        $result = [];
        /**
         * 以每个人去统计
         */
        if (!is_array ($idArr)){
            $idArr = explode (',',$idArr);
        }

        foreach ($idArr as $id) {
            //统计退单
            $tdPrice = 0;
            $yj = 0;
            if ($tdData){
                foreach ($tdData as $tdDatum) {
                    //查询订单信息
                    $daOrder = $this->where (['id'=>$tdDatum['order_company_id'],'certificate_code'=>$tdDatum['certificate_code']])->find ();
                    if ($daOrder){
                        //查看业绩归属人有几人
                        $performanceArr = explode (',', $daOrder['performance_uid']);
                        foreach ($performanceArr as $performanceArrItem) {
                            if ($performanceArrItem == $id){
                                $tdPrice += $tdDatum['performance']/count($performanceArr);
                            }
                        }
                    }
                }
            }
            //统计订单
            foreach ($data as $idDatum) {
                $idArrs = explode (',',$idDatum['performance_uid']);
                $idCount = count($idArrs);
                foreach ($idArrs as $items) {
                    if ($items == $id){
                        $yj += $idDatum['performance']/$idCount;
                    }
                }
            }

            $result[] = [
                'performance_uid'=>$id,
                'all_out_price'=>$yj + $tdPrice
            ];
        }

        return $result;
    }

    /**
     * 成交总数量
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getOrderNumModel($startDate, $endDate, $uidArr): int
    {
        //查询成交时间
        $dealModel = new OrderDeal();
        $count = 0;
        $data = $this->whereRaw('status = 1 OR status = 12')->select()->toArray();
        //判断业绩归属人是否存在uidArr
        if (!is_array($uidArr)) {
            $uidArr = explode(',', $uidArr);
        }

        foreach ($data as $datum) {
            if (empty($datum['performance_uid'])) {
                continue;
            }
            $datumPidArr = explode(',', $datum['performance_uid']);

            $datumPidCount = count($datumPidArr);
            foreach ($uidArr as $item) {
                if (!in_array($item, $datumPidArr)) {
                    continue;
                }
                //查看成交时间
//                $dealData = $dealModel->getOrderCompanyIdFindModel($datum['id'],$datum['certificate_code']);
//                if ($dealData){
                if (strtotime ($datum['create_date']) > strtotime ($startDate) && strtotime ($datum['create_date']) < strtotime ($endDate)) {
                    $count++;
                    break;
                }
//                }
            }
        }
        return $count;
//        return $this->count();
    }

    public function getBusinessIdCountModel($id): int
    {
        return $this->where(['business_id' => $id, 'status' => 2])->count();
    }

    /**
     * 通过证书id查询补全资料
     * @param $cer
     * @return array|null
     */
    public function getExcelInfoModel($cer): ?array
    {
        $data = $this->where(['certificate_code' => $cer])->field('sale_price as get_price')->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }

    /**
     * 业绩总表修改业绩
     * @param $param
     */
    public function editIdPerformanceModel($param)
    {
        return $this->where(['certificate_code' => $param['certificate_code']])->update(['performance' => $param['performance'],'ad_performance'=>1]);
    }

    /**
     * 查询应收款
     * @param $certificate_code
     * @return mixed
     */
    public function getCerGetPriceModel($certificate_code)
    {
        return $this->where(['certificate_code' => $certificate_code])->value('sale_price');
    }

    /**
     * 查询应付款
     * @param $certificate_code
     * @return mixed
     */
    public function getCerOutPriceModel($certificate_code)
    {
        return $this->where(['certificate_code' => $certificate_code])->value('cost_price');
    }

    /**
     * 查询企业名称对等的订单
     * @param $enterprise_name
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getEnterpriseName($enterprise_name)
    {
        return $this->where(['enterprise_name' => $enterprise_name])->select()->toArray();
    }

    public function getInfo($id)
    {
        return $this->where('id', $id)->find();
    }


    /**
     * 查询审核人为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getResponsibilityUidDataModel($id)
    {
        return $this->where(['responsibility_uid' => $id])->column('id');
    }

    public function editResponsibilityUidDataModel($idArr, $id)
    {
        return $this->whereIn('id', $idArr)->update(['responsibility_uid' => $id]);
    }

    /**
     * 查询收证人员为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getGetUidDataModel($id)
    {
        return $this->where(['get_uid' => $id])->column('id');
    }

    public function editGetUidDataModel($idArr, $id, $org)
    {
        return $this->whereIn('id', $idArr)->update(['get_uid' => $id, 'get_org' => $org]);
    }

    /**
     * 查询发起人为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getSubmitUidDataModel($id)
    {
        return $this->where(['submit_id' => $id])->column('id');
    }

    public function editSubmitUidDataModel($idArr, $id)
    {
        return $this->whereIn('id', $idArr)->update(['submit_id' => $id]);
    }

    /**
     * 出证
     * @param $id
     * @return array
     */
    public function getOutUidDataModel($id)
    {
        return $this->where(['out_uid' => $id])->column('id');
    }

    public function editOutUidDataModel($idArr, $id, $org)
    {
        return $this->whereIn('id', $idArr)->update(['out_uid' => $id, 'out_org' => $org]);
    }

    /**
     * 报表中心-提成比列
     * @param $bid
     * @param $uid
     * @param string $startDate
     * @param string $endDate
     * @return float|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTcblModel($bid, $uid, string $startDate, string $endDate)
    {
//        $bid = 176;
//        $uid = 172;

        $data = $this->where(['business_id' => $bid])->whereBetweenTime('create_date', $startDate, $endDate)->field('performance_uid')->select()->toArray();

        //查询业绩归属人是否包含当前uid
        $performance = 0;
        if ($data) {
            foreach ($data as $datum) {
                $perUidArr = explode(',', $datum['performance_uid']);
                foreach ($perUidArr as $value) {
                    if ($value == $uid) {
                        $performance += $datum['performance'] / count($perUidArr);
                    }
                }
            }
        }
        return $performance;
    }

    /**
     * 业绩总表添加备注
     * @param $param
     */
    public function editIdLabelModel($param)
    {
        return $this->where(['id'=>$param['id'],'certificate_code'=>$param['certificate_code']])->update (['label'=>$param['label']]);
    }

    /**
     * 查询今日订单个数
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getToDayCountFindModel():int
    {
        return  $this->whereDay('create_date')->count ();
    }

}